<template>
  <div>
    <!-- 上部分 -->
    <el-form :model="form" :rules="rules" ref="formRef"
             :style="{ backgroundColor: 'white', margin: '5px', padding: '10px',borderRadius:'10px' }">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="请选择" prop="value" style="width: 100%;">
            <el-select v-model="form.value" placeholder="请选择" style="width: 100%;">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="采集开始时间" prop="value1" style="width: 100%;">
            <el-date-picker v-model="form.value1" type="datetime" placeholder="选择日期时间" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="采集结束时间" prop="value2" style="width: 100%;">
            <el-date-picker v-model="form.value2" type="datetime" placeholder="选择日期时间" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="手工名称" prop="name1" style="width: 100%;">
            <el-input v-model="form.name1" style="width: 100%;"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="原视频名称" prop="name2" style="width: 100%;">
            <el-input v-model="form.name2" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="2" style="text-align: right;">
        <el-form-item style="width: 100%;">
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-col>
    </el-form>

    <!-- 下部分 -->
    <el-row :style="{ backgroundColor: 'white', margin: '10px', padding: '10px', borderRadius: '10px' }">
      <el-col :span="24">
        <el-table :data="tableData" style="width: 100%; overflow-x: auto;">
          <el-table-column prop="clay_material" label="类型" fixed></el-table-column>
          <el-table-column prop="filename" label="编号" fixed></el-table-column>
          <!-- 动态列渲染 segments -->
          <el-table-column
              v-for="(segment, index) in getSegmentColumns()"
              :key="index"
              :label="'片段' + (segment)"
              :prop="'segments.' + (segment)"
          >
            <template #default="scope">
              <div v-if="scope.row['segments'][segment] && scope.row['segments'][segment].length > 0" style="text-align: center">
                <div v-for="(item, i) in scope.row['segments'][segment]" :key="i" style="display: flex;align-items: center;justify-content: space-between">
                  <el-tooltip
                      class="box-item"
                      effect="dark"
                      :content="item.out_paths"
                      placement="bottom"
                  >
                    <el-button @click="playVideo(item.out_paths)">{{ item.name }}</el-button>
                  </el-tooltip>
                  <el-icon :size="20">
                    <CircleClose v-if="item.out_paths" @click="deleteVideo(item.out_paths)"/>
                    <Upload v-else @click="deleteVideo(item.out_paths)"/>
                  </el-icon>
                </div>
              </div>
              <div v-else style="text-align: center">
                <el-icon :size="20">
                  <Upload @click="deleteVideo([])"/>
                </el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <div class="button-container">
                <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">添加花絮控件</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-dialog v-model="dialogFormVisible" title="添加花絮控件">
      添加前缀
      <el-row>
        <el-form :model="preFacingAudio">
          <el-form-item label="视频文件" prop="video" :label-width="formLabelWidth">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                action="http://192.168.0.47:5001"
                :file-list="preFacingAudio.video"
                accept="video/*"
                :auto-upload="true"
                :on-change="handleChangeVideo"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="字幕" prop="subtitles" :label-width="formLabelWidth">
            <el-input v-model="preFacingAudio.subtitles" placeholder="请上传字幕"></el-input>
          </el-form-item>
          <el-form-item label="上传音频文件" :label-width="formLabelWidth">
            <el-upload
                ref="upload"
                class="upload-demo"
                action="http://192.168.0.47:5001"
                :on-change="handleChangeAudio"
                :limit="1"
                :file-list="preFacingAudio.audio_file"
                :auto-upload="true"
                accept=".mp3,.wav"
            >
              <template #trigger>
                <el-button type="primary">上传音频</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-row>
      添加后缀
      <el-row>
        <el-form :model="rearAudio">
          <el-form-item label="视频文件" prop="video" :label-width="formLabelWidth">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                action="http://192.168.0.47:5001"
                :file-list="rearAudio.video"
                accept="video/*"
                :auto-upload="true"
                :on-change="handleChangeSecondVidio"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="字幕" prop="subtitles" :label-width="formLabelWidth">
            <el-input v-model="rearAudio.subtitles" placeholder="请上传字幕"></el-input>
          </el-form-item>
          <el-form-item label="上传音频文件" :label-width="formLabelWidth">
            <el-upload
                ref="upload"
                class="upload-demo"
                action="http://192.168.0.47:5001"
                :on-change="handleChangeSecondAudio"
                :limit="1"
                :file-list="rearAudio.audio_file"
                :auto-upload="true"
                accept=".mp3,.wav"
            >
              <template #trigger>
                <el-button type="primary">上传音频</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </el-row>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="okToAdd">确定</el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="videoDialogVisible"
        width="700px"
        @close="closeVideoDialog"
        title="视频播放"
        center
    >
      <div style="display: flex; justify-content: center;">
        <video v-if="currentVideo" controls autoplay style="max-width: 100%;height: 400px;margin: 30px">
          <source src="@/assets/video(1).mp4" type="video/mp4"/>  <!-- 动态绑定 src 属性 -->
          您的浏览器不支持 HTML5 视频播放。
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import * as dayjs from 'dayjs'
import {home} from '@/api/home.ts'
import {CircleClose, Upload} from "@element-plus/icons-vue";
import videojs from 'video.js';
import 'video.js/dist/video-js.css';

const loading = ref(false) // 添加 loading 状态

onMounted(() => {
  getPoltType()
  getTableData()
})

const formRef = ref()
const form = reactive({
  value: '',
  value1: '',
  value2: '',
  name1: '',
  name2: '',
})

// 搜索
const search = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true // 设置 loading 为 true
      console.log(form)
      home.getSearch(form.value, dayjs(form.value1).format('YYYY-MM-DD HH:mm:ss'), dayjs(form.value2).format('YYYY-MM-DD HH:mm:ss'), form.name1, form.name2).then((res) => {
        console.log(res.data)
        // 将搜索返回值赋值给 tableData
        tableData.value = res.data
        ElMessage.success('搜索成功！')
      }).finally(() => {
        loading.value = false // 设置 loading 为 false
      })
    } else {
      console.log('表单验证失败')
    }
  })
}

const typeList = reactive<any[]>([])
const getPoltType = () => {
  loading.value = true // 设置 loading 为 true
  home.getPoltType().then((res) => {
    console.log(res.data)
    typeList.push(...res.data)
  }).finally(() => {
    loading.value = false // 设置 loading 为 false
  })
}
// 获取所有非空的 segments 索引
const getSegmentColumns = () => {
  let segmentColumns = [];
  console.log(tableData.value)
  tableData.value.forEach(row => {
    Object.keys(row.segments).forEach(key => {
      const segmentKey = Number(key);
      if (segmentKey !== -1 && row.segments[key].length > 0 && !segmentColumns.includes(segmentKey)) {
        segmentColumns.push(segmentKey);
      }
    });
  });
  return segmentColumns.sort((a, b) => a - b);
}
const tableData = ref<any[]>([])

// 修改: 确保 segments 的正确处理
const getTableData = () => {
  loading.value = true // 设置 loading 为 true
  home.getFindMissingSteps().then((res) => {
    console.log(res.data)
    tableData.value = res.data
  }).catch((error) => {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }).finally(() => {
    loading.value = false // 设置 loading 为 false
  })
}
const rules = reactive({
  value: [
    {required: true, message: '请选择一个选项', trigger: 'change'}
  ],
  value1: [
    {required: true, message: '请选择采集开始时间', trigger: 'change'}
  ],
  value2: [
    {required: true, message: '请选择采集结束时间', trigger: 'change'}
  ],
  name1: [
    {required: true, message: '请输入手工名称', trigger: 'blur'}
  ],
  name2: [
    {required: true, message: '请输入原视频名称', trigger: 'blur'}
  ]
})

const formLabelWidth = '140px'
const handleEdit = (row: any, index: number) => { // 修改参数
  dialogFormVisible.value = true
}
const dialogFormVisible = ref(false)

// 添加视频参数
const preFacingAudio = reactive({
  video: [] as any[],
  subtitles: '',
  audio_file: [] as any[],
})

const handleChangeVideo = (file: any, fileList: any[]) => {
  console.log('File changed:', file, fileList)
  preFacingAudio.video = fileList
}

const handleChangeAudio = (file: any, fileList: any[]) => {
  console.log('File changed:', file, fileList)
  preFacingAudio.audio_file = fileList
}

const rearAudio = reactive({
  video: [] as any[],
  subtitles: '',
  audio_file: [] as any[],
})

const handleChangeSecondVidio = (file: any, fileList: any[]) => {
  console.log('File changed:', file, fileList)
  rearAudio.video = fileList
}

const handleChangeSecondAudio = (file: any, fileList: any[]) => {
  console.log('File changed:', file, fileList)
  rearAudio.audio_file = fileList
}

const okToAdd = async () => {
  loading.value = true // 设置 loading 为 true
  const formDataArray = []

  // 创建第一个 formData (preFacingAudio)
  const formData1 = new FormData()
  preFacingAudio.video.forEach((file) => formData1.append('video', file.raw))
  preFacingAudio.audio_file.forEach((file) => formData1.append('audio_file', file.raw))
  formData1.append('subtitles', preFacingAudio.subtitles)
  formDataArray.push(formData1)

  // 创建第二个 formData (rearAudio)
  const formData2 = new FormData()
  rearAudio.video.forEach((file) => formData2.append('video', file.raw))
  rearAudio.audio_file.forEach((file) => formData2.append('audio_file', file.raw))
  formData2.append('subtitles', rearAudio.subtitles)
  formDataArray.push(formData2)

  home.getAddATriviaControl(formDataArray).then(() => {
    ElMessage.success('添加成功！')
  }).finally(() => {
    loading.value = false // 设置 loading 为 false
  })
}

// 新增方法：获取 segments 的键
const getSegmentKeys = (segments: any) => {
  return Object.keys(segments).map(Number).sort((a, b) => a - b);
}

const videoDialogVisible = ref(false) // 控制视频弹窗显示与隐藏
const currentVideo = ref('')       // 当前播放视频的路径
// 点击按钮时播放视频
const playVideo = (videoPath: any) => {
  if (typeof videoPath === 'string' && videoPath.trim() !== '') {
    currentVideo.value = videoPath;  // 设置当前视频路径
    videoDialogVisible.value = true; // 显示视频弹窗
  } else {
    console.error('Invalid video path:', videoPath);
    ElMessage.error('视频路径无效，请检查视频路径。');
  }
}
// 关闭视频弹窗
const closeVideoDialog = () => {
  currentVideo.value = '';         // 清空当前视频路径
}

// 新增 deleteVideo 方法
const deleteVideo = (outPaths: string[]) => {
  // 这里添加删除视频的逻辑
  console.log('Deleting video:', outPaths)
  // 示例：调用 API 删除视频
  // home.deleteVideo(outPaths).then(() => {
  //   ElMessage.success('视频删除成功！')
  // }).catch((error) => {
  //   console.error('删除视频失败:', error)
  //   ElMessage.error('删除视频失败')
  // })
}
</script>

<style scoped>
.demo-date-picker {
  display: flex;
  padding: 0;
}

.demo-date-picker .demonstration {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
  padding-left: 2px;
}
</style>